home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2188 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.1 KB

  1. Path: io.UWinnipeg.ca!wsimpson
  2. From: Bill Simpson <wsimpson@uwinnipeg.ca>
  3. Newsgroups: comp.lang.c
  4. Subject: quick decision: is n a power of 2?
  5. Date: Fri, 19 Jan 1996 12:00:01 -0600
  6. Organization: The University of Manitoba
  7. Message-ID: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca>
  8. NNTP-Posting-Host: io.uwinnipeg.ca
  9. Mime-Version: 1.0
  10. Content-Type: TEXT/PLAIN; charset=US-ASCII
  11.  
  12. Is there a fast way to decide whether a number n is a power of 2?
  13.  
  14. In my problem
  15. if ((high-low+1) is a power of 2)
  16.     {
  17.     do one thing
  18.     }
  19. else
  20.     {
  21.     do another
  22.     }
  23. e.g. low=0, high=7: 7-0+1 is a power of 2.
  24.  
  25. The only thing I have thought of is that if n is power of 2
  26. log(n)/log(2) is an integer
  27. BUT this is going to be a SLOW computation.  Needs to be fast.
  28.  
  29. Since I am dealing with unsigned long ints, I guess I can just store all
  30. 31 powers of 2 in a table and compare to n.  Though I don't know a fast
  31. algorithm to compare a number to 31 numbers in an array.
  32.  
  33. Perhaps there is a tricky nonportable way to see if I have power-of-2 by 
  34. looking at bits?  (That is fine for this application)
  35.  
  36. Thanks very much for any help.
  37.  
  38. Bill Simpson
  39.